package com.zoweunion.mechanic.service.app.impl;

import com.zoweunion.mechanic.dao.app.AppOwnerDataStatisticsDao;
import com.zoweunion.mechanic.dao.app.OrderDao;
import com.zoweunion.mechanic.entity.WorkHourSumEntity;
import com.zoweunion.mechanic.service.app.AppOwnerDataStatisticsService;
import com.zoweunion.mechanic.service.base.BaseService;
import com.zoweunion.mechanic.util.MyException;
import com.zoweunion.mechanic.util.Orgin;
import com.zoweunion.mechanic.util.constants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.zoweunion.mechanic.service.app.impl.OrderServicelmpl.createYMD;

@Service
@SuppressWarnings("unchecked")
@Transactional
public class AppOwnerDataStatisticsServiceImpl extends BaseService implements AppOwnerDataStatisticsService {

    @Autowired
    private AppOwnerDataStatisticsDao appOwnerDataStatisticsDao;
    @Autowired
    private OrderDao orderDao;

    /**
     * 设备信息（app看板）
     * @body reqMap
     * 这里边传参时，type为1表示车主，type为2表示服务商
     * @return
     * @throws MyException
     */
    @Override
    public Map<String, Object> deviceInfo(Map<String, Object> reqMap) {

        Map<String, Object> deviceInfo = new HashMap<>();

        // 获取今日总工时和总油耗
        Map<String, Object> workAndOil = appOwnerDataStatisticsDao.workAndOil(reqMap);

        // 获取今日故障代码发生的次数
        Integer fault = appOwnerDataStatisticsDao.fault(reqMap);

        // 获取今日开工的设备数
        Integer workingDevice = appOwnerDataStatisticsDao.workingDevice(reqMap);

        // 获取车主/服务商的总设备数
        Integer totalDevice = appOwnerDataStatisticsDao.totalDevice(reqMap);

        deviceInfo.putAll(workAndOil);
        deviceInfo.put("fault", fault);
        deviceInfo.put("workingDevice", workingDevice);
        deviceInfo.put("totalDevice", totalDevice);

        return deviceInfo;
    }

    /**
     * 工单信息(app看板)
     * @body reqMap
     * 这里边传参时，type为1表示车主，type为2表示服务商
     * @return
     * @throws MyException
     */
    @Override
    public Map<String, Object> orderInfo(Map<String, Object> reqMap) {
        Map<String, Object> orderInfo = appOwnerDataStatisticsDao.orderInfo(reqMap);
        return orderInfo;
    }

    /**
     * 工时油耗平均统计
     * 不通过特殊传参字段做判断，仅通过是否传oId和cId判断是否为车主账号或是单一车辆
     */
    @Override
    public Map<String, Object> workFuelAverage(Map<String, Object> params) {

        // 如果有cId把oId移除，查询单独一辆车
        if (params.containsKey("cId")) {

            if (!params.get("cId").toString().isEmpty()) {

                params.remove("oId");
                params.remove("s_id");
            }
        }
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("workHourAverage",0);
        hashMap.put("fuelAverage",0);
        // 计算总平均工时，总平均油耗
        Map<String, Object> selectAverage = appOwnerDataStatisticsDao.selectAllAverage(params);
        if (selectAverage!=null){
            hashMap.putAll(selectAverage);
        }
        Date startTime = Orgin.getDate(params, "startTime");
        Date endTime = Orgin.getDate(params, "endTime");
        int type = Orgin.getIntValue(params, "type");
        List<Map<String, Object>> arrayList = new ArrayList<>();

//        type: 1是表示月的情况，2是表示年的情况
//        startTime: 开始时间
//        endTime: 结束时间
//        modelId: 车型id
//        provinceCode: 省份的id
        // type 1 是日

        if (type==1){
            List<String> ymd = createYMD(startTime, endTime);
            ymd.forEach(item -> {
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                stringObjectHashMap.put("fuelAverage",0);
                stringObjectHashMap.put("workHourAverage",0);
                stringObjectHashMap.put("date",item);
//                params.put("ymd",item);
//                //计算平均工时和平均油耗的，如果是车主账号，就会传参oId，并且如果是车主选择车辆或者是具体车辆则会传参cId
//                Map<String, Object> stringObjectMap = appOwnerDataStatisticsDao.workFuel(params);
//                if(stringObjectMap!=null){
//                    stringObjectHashMap.putAll(stringObjectMap);
//                }
                arrayList.add(stringObjectHashMap);
            });

            //计算平均工时和平均油耗的，如果是车主账号，就会传参oId，并且如果是车主选择车辆或者是具体车辆则会传参cId
            List<Map<String, Object>> stringObjectMap = appOwnerDataStatisticsDao.workFuelList(params);
            arrayList.forEach(item1->{
                stringObjectMap.forEach(item2->{
                    if (item2.get("date").toString().equals(item1.get("date"))) {
                        item1.put("fuelAverage",item2.get("fuelAverage"));
                        item1.put("workHourAverage",item2.get("workHourAverage"));
                    }
                });
            });

        }
        // type 2 是月份的
        else if(type==2){
            LocalDate today = startTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            for(long i = 0L;i <= 11L; i++){
                LocalDate localDate = today.plusMonths(i);
                String item = localDate.toString().substring(0,7);
                params.put("ymdS",item+"-01");
                params.put("ymdE",item+"-31");
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                stringObjectHashMap.put("fuelAverage",0);
                stringObjectHashMap.put("workHourAverage",0);
                stringObjectHashMap.put("date",item);
                //计算平均工时和平均油耗的，如果是车主账号，就会传参oId，并且如果是车主选择车辆或者是具体车辆则会传参cId
                Map<String, Object> stringObjectMap = appOwnerDataStatisticsDao.workFuel(params);
                if(stringObjectMap!=null){
                    stringObjectHashMap.putAll(stringObjectMap);
                }
                arrayList.add(stringObjectHashMap);
            }
        }
        hashMap.put("datalist",arrayList);
        return hashMap;
    }

    /**
     * 车辆工时占比
     * type为2表示车主，显示车辆名称；type为1表示服务商，显示车主名称
     */
    @Override
    public List<WorkHourSumEntity> workingHoursPer(Map<String, Object> params) {
        //计算的是总工时（取前10），type为2表示车主，显示车辆名称；type为1表示服务商，显示车主名称
        List<WorkHourSumEntity> workingHoursPer = appOwnerDataStatisticsDao.workingHoursPer(params);
//        //计算前10的总工时的总工时
//        Double total = workingHoursPer.stream().mapToDouble(WorkHourSumEntity::getOwnerWorkHourSum).sum();
//        workingHoursPer.forEach(item ->{
//            //计算前10的各自占比
//            BigDecimal b = new BigDecimal(item.getOwnerWorkHourSum()/total);
//            Double per = b.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
//            item.setPer(per);
//        });
        return workingHoursPer;
    }

    /**
     * 额度预警
     * @return
     * @throws MyException
     */
    @Override
    public Map<String, Object> quotaWarning(String oId) {
        Map<String, Object> quotaWarn = new HashMap<>();
        quotaWarn.put("totalQuota", 0);
        quotaWarn.put("surplusQuota", 0);
        quotaWarn.put("usedQuota", 0);
        quotaWarn.put("usedProportion", 0);
        Map<String, Object> quotaWarning = appOwnerDataStatisticsDao.quotaWarning(oId);
        if (null != quotaWarning) {
            quotaWarn.putAll(quotaWarning);
        }
        return quotaWarn;
    }

    /**
     * 维修统计
     * @param
     * @return
     * @throws MyException
     */
    @Override
    public Map<String, Object> maintenanceStatistics(Map<String, Object> reqMap) {
        Map<String, Object> completeOrderPer = appOwnerDataStatisticsDao.maintenanceStatistics(reqMap);
        return completeOrderPer;
    }

    /**
     * 额度预警（服务商）
     * @param
     * @return
     * @throws MyException
     */
    @Override
    public Map<String, Object> quotaWarningPer(String sId) {
        Map<String, Object> quotaWarningPer = new HashMap<>();
        quotaWarningPer.put("warningPer", 0);
        quotaWarningPer.put("warningCount", 0);
        quotaWarningPer.put("totalCount", 0);
        List<Map<String, Object>> quotaList = appOwnerDataStatisticsDao.quotaWarningPer(sId);
        if (null!= quotaList && quotaList.size() >0 ) {
            quotaWarningPer.put("totalCount", quotaList.size());
            for (Map<String, Object> quota : quotaList) {

                // 获取用户还款总额度
                Double orderRepaymentSum = 0.0;
                // 获取用户使用总额度
                Double orderUseSum = 0.0;

                if (orderDao.getOrderRepaymentSum(quota) != null) {

                    orderRepaymentSum = Math.ceil(orderDao.getOrderRepaymentSum(quota));
                }

                if (orderDao.getOrderUseSum(quota) != null) {

                    orderUseSum = Math.ceil(orderDao.getOrderUseSum(quota));
                }

                if (((Orgin.getDouble(quota, "creditLimit") - (orderUseSum - orderRepaymentSum)) / Orgin.getDouble(quota, "creditLimit")) < 0.2) {
                    quotaWarningPer.put("warningCount", Orgin.getInteger(quotaWarningPer, "warningCount") + 1);
                }
            }
            quotaWarningPer.put("warningPer", String.format("%.2f", Orgin.getDouble(quotaWarningPer, "warningCount") / Orgin.getDouble(quotaWarningPer, "totalCount")));
        }
        return quotaWarningPer;
    }

    /**
     * 营收统计
     * 这里边传参时，type为1是日，type为2表示月份
     * @param
     * @return
     * @throws MyException
     */
    @Override
    public Map<String, Object> revenueStatistics(Map<String, Object> reqMap) throws MyException {

        LocalDate dateS = LocalDate.parse(reqMap.get("startTime").toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate dateE = LocalDate.parse(reqMap.get("endTime").toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (dateS.isAfter(dateE)) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "开始日期必须小于结束日期");
        }

        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("totalRevenue",0);
        // 计算总营收
        Double selectTotalRevenue = appOwnerDataStatisticsDao.selectTotalRevenue(reqMap);
        if (selectTotalRevenue != null){
            hashMap.put("totalRevenue", selectTotalRevenue);
        }
        Date startTime = Orgin.getDate(reqMap, "startTime");
        Date endTime = Orgin.getDate(reqMap, "endTime");
        int type = Orgin.getIntValue(reqMap, "type");
        List<Map<String, Object>> arrayList = new ArrayList<>();

//        type: 1是表示月的情况，2是表示年的情况
//        startTime: 开始时间
//        endTime: 结束时间
        // type 1 是日
        if (type==1){
            List<String> ymd = createYMD(startTime, endTime);
            ymd.forEach(item -> {
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                stringObjectHashMap.put("revenue",0);
                stringObjectHashMap.put("date",item);
//                reqMap.put("ymd",item);
//                //计算营收的
//                Double stringObjectMap = appOwnerDataStatisticsDao.revenue(reqMap);
//                if(stringObjectMap != null){
//                    stringObjectHashMap.put("revenue", stringObjectMap);
//                }
                arrayList.add(stringObjectHashMap);
            });

            //计算营收的
            List<Map<String, Object>> stringObjectMap = appOwnerDataStatisticsDao.revenueList(reqMap);
            arrayList.forEach(item1->{
                stringObjectMap.forEach(item2->{
                    if (item2.get("date").toString().equals(item1.get("date"))) {
                        item1.put("revenue",item2.get("revenue"));
                    }
                });
            });

        }
        // type 2 是月份的
        else if(type==2){
            LocalDate today = startTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            for(long i = 0L;i <= 11L; i++){
                LocalDate localDate = today.plusMonths(i);
                String item = localDate.toString().substring(0,7);
                reqMap.put("ymd",item+"-00");
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                stringObjectHashMap.put("revenue",0);
                stringObjectHashMap.put("date",item);
                //计算营收的
                Double stringObjectMap = appOwnerDataStatisticsDao.revenue(reqMap);
                if(stringObjectMap!=null){
                    stringObjectHashMap.put("revenue", stringObjectMap);
                }
                arrayList.add(stringObjectHashMap);
            }
        }
        hashMap.put("datalist",arrayList);
        return hashMap;
    }

    /**
     * 车主获取车辆数据
     * @param
     * @return
     */
    @Override
    public List<Map<String, Object>> carListByOwner(Map<String, Object> reqMap) {
        List<Map<String, Object>> carListByOwner = appOwnerDataStatisticsDao.carListByOwner(reqMap);
        return carListByOwner;
    }
}
